package com.hp.gxw.config;

import com.hp.gxw.entity.SysUser;
import com.hp.gxw.shiro.LoginType;
import com.hp.gxw.shiro.UserToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * session 拦截设置用户信息及记住我状态该为登录状态
 * 
 * @author blink
 *
 */
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
		try {
			Subject subject = SecurityUtils.getSubject();
			// 判断用户是通过记住我功能自动登录,此时session失效
			SysUser user = (SysUser)SecurityUtils.getSubject().getPrincipal();
			if (!subject.isAuthenticated() && subject.isRemembered()) {
				// 执行认证登陆
				UserToken token = new UserToken(user.getUserCode(), user.getUserPassword(), true, LoginType.FREE.getDesc());
				// 执行认证登陆
				try {
					subject.login(token);
				} catch (Exception e) {
					log.error("记住我状态改为登录状态失败", e);
					return false;
				}
			}
			if ((subject.isAuthenticated() || subject.isRemembered()) && (subject.getSession().getAttribute("user") == null)) {
				Session session = SecurityUtils.getSubject().getSession();
				session.setAttribute("user", user);
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

}